const axios = require('axios');

const loginDao = require('../dao/loginDao');
const { createUserJwtToken } = require('../util/server_jwt');
const { wx } = require('../util/server_config');
const { appid, secret } = wx;

const config = require('../config');

const Response = require('../entity/http/Response');

const loginService = {
    /**
     * 微信登录
     */
    async wechatLogin(wxLogin) {
        // 获取临时登录凭证
        let code = wxLogin.code;
        // 向微信服务器发请求获取用户信息
        let data;
        try {
            const response = await axios.get(`https://api.weixin.qq.com/sns/jscode2session`, {
                params: {
                    appid: appid,
                    secret: secret,
                    js_code: code,
                    grant_type: 'authorization_code'
                }
            });
            data = response.data;
            if (data.errcode) {
                return (new Response()).fail(500, "获取用户信息失败");
            }
        } catch (error) {
            console.log(error);
            return (new Response()).fail(500, "获取用户信息失败");
        }
        // 获取openid
        let openid = data.openid;
        // 验证登录
        let result;
        try {
            let tmp = await loginDao.loginByOpenid(openid);
            if (tmp.length == 0) {
                tmp = await loginDao.addUser(openid, wxLogin);
            }
            
            // 生成jwt令牌
            let payload = { uid: tmp[0].id, name: tmp[0].name };
            // 将 jwt令牌 的有效时间设置为 20小时
            let jwt = await createUserJwtToken(payload, {expiresIn: config.token.expireTime});
            
            // 返回数据
            result = (new Response()).ok("操作成功", {
                token: jwt,
                userInfo: tmp[0]
            });
        } catch (err) {
            result = (new Response()).fail(500, "数据库异常");
        }
        return result;
    },
};

module.exports = loginService;